package commands;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

import org.pircbotx.Channel;
import org.pircbotx.User;

import backend.Bot;
import backend.Util;

public class ConvertCommand extends Command
{
	@Override
	protected void initialize()
	{
		addAlias("convert");
		setName("Convert");
		setHelpText("Convert between number bases or character sets. Available parameters: bin/binary, oct/octal, dec/decimal, 2-36, ascii");
		setUsableInPM(true);
	}

	@Override
	public void execute(Bot bot, Channel chan, User user, String message)
	{
		if(Util.hasArgs(message, 4))
		{
			String[] cmd = Util.getArgs(message, 4);
			int from = getBase(cmd[1]);
			int to = getBase(cmd[2]);
			if(from != -1)
			{
				System.out.println(cmd[1] + " " + from);
				BigInteger data = new BigInteger(cmd[3], from);		
				if(to != -1)
				{
					String output = data.toString(to);
					passMessage(bot, chan, user, "Base-"+from+" to Base-"+to+": "+output);
				}
				else
				{
					if(cmd[2].equalsIgnoreCase("ascii"))
					{
						CharBuffer buffer = Charset.defaultCharset().decode(ByteBuffer.wrap(data.toByteArray()));
						passMessage(bot, chan, user, "Base-"+from+" to Ascii: "+buffer.toString());	
					}
					else
					{
						passMessage(bot, chan, user, cmd[2] + " is an invalid parameter.");
					}
				}
			}
			else
			{
				if(cmd[1].equalsIgnoreCase("ascii"))
				{
					
					// TODO: use the right charset
					byte[] bytes = cmd[3].getBytes();
					StringBuffer output = new StringBuffer();
					for(int k=0;k<bytes.length;k++)
					{
						if(k != 0)
							output.append(' ');
						output.append(Integer.toString(((int)bytes[k]), to));
					}
					passMessage(bot, chan, user, "Ascii to Base-"+to+": "+output);	
				}
				else
				{
					passMessage(bot, chan, user, cmd[1] + " is an invalid parameter.");
				}
			}
		}
		else
		{
			invalidFormat(bot, chan, user);
		}
	}
	
	@Override
	protected String format()
	{
		return super.format() + "[from] [to] [data]";
	}
	
	private int getBase(String str)
	{
		if(str.equalsIgnoreCase("dec") || str.equalsIgnoreCase("decimal"))
			return 10;
		else if(str.equalsIgnoreCase("hex") || str.equalsIgnoreCase("hexadecimal"))
			return 16;
		else if(str.equalsIgnoreCase("oct") || str.equalsIgnoreCase("octal"))
			return 8;
		else if(str.equalsIgnoreCase("bin") || str.equalsIgnoreCase("binary"))
			return 2;
		else
		{
			try
			{
			return Integer.parseInt(str);
			} catch (NumberFormatException e) { } //just try it
		}
		return -1;
	}
}
